﻿using RQX.Common.Core.Extension;
using RQX.Common.Core.File;
using RQX.Common.Core.Hardware.BaseCollection;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace DataCollection.ChangeCode
{
    public partial class CodeManage : Form
    {
        public CodeManage()
        {
            InitializeComponent();
        }

        private void CodeManage_Load(object sender, EventArgs e)
        {
            //绑定设备类型
            var typeList = CodeInfo.list.GroupBy(k => k.DeviceType).Select(k => k.Key).ToList();
            ddl_device_type.DataSource = typeList;
            if (ddl_device_type.Items.Count > 0)
            {
                ddl_device_type.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// 获取gridview数据
        /// </summary>
        private void BindGridView()
        {
            //code、name、desc、low、high、collectionname
            var deviceType = ddl_device_type.Text;
            var plugName = ddl_plug_name.Text;

            grid.Rows.Clear();
            CodeInfo.list.Where(k => k.DeviceType.Equals(deviceType)).ForEach(item =>
            {
                var collectionName = item.SourceCode?.Find(k => k.PlugName.Equals(plugName))?.CollectionName;
                grid.Rows.Add(item.Code, item.Name, item.Desc, item.Low, item.High, collectionName);
            });
        }
        /// <summary>
        /// devicetype选中联动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ddl_device_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            var deviceType = ddl_device_type.Text;
            //绑定插件类型,从配置文件中获取
            List<string> plugList = new List<string>();
            CodeInfo.list.Where(k => k.DeviceType.Equals(deviceType)).ForEach(item =>
              {
                  var plugNames = item.SourceCode?.Select(k => k.PlugName);
                  plugNames?.ForEach(name => plugList.Add(name));
              });
            //从插件目录中获取
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
            var files = FileUtils.GetAllFiles(path);
            files.ForEach(file =>
            {
                try
                {
                    var assembly = Assembly.LoadFrom(file.FullName);
                    var type = assembly.GetTypes().Find(k => !k.IsAbstract && k.IsPublic && typeof(IIocCollection).IsAssignableFrom(k));
                    if (type.IsNotNull())
                    {
                        if (((IIocCollection)Activator.CreateInstance(type)).DeviceType.ToString().Equals(deviceType))
                        {
                            plugList.Add(file.Name);
                        }
                    }
                }
                catch { }
            });

            ddl_plug_name.DataSource = plugList.Distinct().ToList();
            if (ddl_plug_name.Items.Count > 0)
            {
                ddl_plug_name.SelectedIndex = 0;
            }
            else
            {
                ddl_plug_name.Text = "";
                BindGridView();
            }
        }
        /// <summary>
        /// 插件选中联动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ddl_plug_name_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGridView();
        }
        /// <summary>
        /// 开始修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            var plugName = ddl_plug_name.Text;
            if (plugName.IsNullOrEmpty())
            {
                FormUtils.ShowMsg("请选择要对码的插件！");
                e.Cancel = true;
            }
        }
        /// <summary>
        /// 修改结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var plugName = ddl_plug_name.Text;
            var code = grid.Rows[e.RowIndex].Cells["dgv_code"].Value.ToString();
            var value = grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();
            var info = CodeInfo.list.Find(k => k.Code == Convert.ToInt32(code));
            var item = info.SourceCode?.Find(k => k.PlugName.Equals(plugName));
            if (item.IsNull())
            {
                info.SourceCode.Add(new SourceCode() { PlugName = plugName, CollectionName = value });
            }
            else
            {
                item.CollectionName = value;
            }
            CodeInfo.Save();
        }

        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN)
            {
                switch (keyData)
                {
                    case Keys.Escape:
                        this.Close();//esc关闭窗体
                        break;
                }
            }
            return false;
        }
    }
}
